package com.litong.utils.http.alithttpclient;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import com.litong.utils.io.IOUtils;

/**
 * 接口调用工具类 目前支持 GET POST请求两种方式
 */
public class HttpURLConnectionUtil {

  /**
   * get请求
   * 
   * @param url
   * @param param
   * @return
   */
  public static String get(String url, Map<String, String> param) {
    URL httpURL = initHttpURL(url, param);
    StringBuffer sb = new StringBuffer();
    try {
      HttpURLConnection httpConnection = (HttpURLConnection) httpURL.openConnection();
      httpConnection.setRequestMethod("GET");
      httpConnection.setRequestProperty("Accept", "application/json");
      if (httpConnection.getResponseCode() != 200) {
        throw new RuntimeException("HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
      }
      sb = IOUtils.toStringBuffer(httpConnection.getInputStream());
    } catch (IOException e) {
      e.printStackTrace();
    }
    return sb.toString();
  }

  private static URL initHttpURL(String url) {
    try {
      return new URL(url);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    return null;
  }

  private static URL initHttpURL(String url, Map<String, String> param) {
    StringBuffer params = buildHttpQueryParams(param);
    try {
      return new URL(url + (params.length() > 0 ? "?" + params.toString() : ""));
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    }
    return null;
  }

  /**
   * 向指定URL发送post请求
   */
  public static String post(String url, Map<String, String> param) {
    StringBuffer params = buildHttpQueryParams(param);
    StringBuffer sb = null;
    // 创建连接
    URL httpURL = initHttpURL(url);
    HttpURLConnection httpConn = null;
    try {
      httpConn = (HttpURLConnection) httpURL.openConnection();
      // 设置参数
      httpConn.setDoOutput(true); // 需要输出
      httpConn.setDoInput(true); // 需要输入
      httpConn.setUseCaches(false); // 不允许缓存
      httpConn.setRequestMethod("POST"); // 设置POST方式连接
      httpConn.setInstanceFollowRedirects(true); // 设置跟随重定向
      // 连接,也可以不用明文connect，使用下面的httpConn.getOutputStream()会自动connect
      httpConn.connect();

      // 建立输入流，向指向的URL传入参数 ,支持的格式是 key=value&key=value
      DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
      dos.writeBytes(params.toString());
      dos.flush();
      dos.close();
      // 读取响应
      if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        sb = IOUtils.toStringBuffer(httpConn.getInputStream());
      } else {
        throw new RuntimeException(
            "HTTP POST Request Failed with Error code : " + httpConn.getResponseCode() + "," + url);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpConn.disconnect();// 断开连接
    }
    return sb.toString();
  }

  @SuppressWarnings("deprecation")
  private static StringBuffer buildHttpQueryParams(Map<String, String> param) {
    StringBuffer sb = new StringBuffer();
    for (Entry<String, String> e : param.entrySet()) {
      sb.append(e.getKey() + "=" + URLEncoder.encode(e.getValue().toString()) + "&");
    }
    if (sb.length() > 0) {
      sb.deleteCharAt(sb.lastIndexOf("&"));
    }
    return sb;
  }
}